# -*- coding: utf-8 -*-

import os,stat

import file_system
from file_system import FileInfo ,FileStore,FileSystem
from path import Path2

class LocalFileStore(FileStore):
    def __init__(self,path,fileSystem):
        '''__init__(Path path,LocalFileSystem fileSystem)'''
        
        self._path=path
        self._fileSystem=fileSystem
    
    def getChild(self,name):
        return LocalFileStore(self._path.append(name),self._fileSystem)
    
    def getChildNames(self):
        return os.listdir(self._getLocalPath())

    def getName(self):
        return self._path.getLastSegment()
    
    def _getLocalPath(self):
        return str(self._path)
    
    def makedir(self):
        if not os.path.exists(self._getLocalPath()):
            os.makedirs(self._getLocalPath())
    
    def getParent(self):
        return LocalFileStore(self._path.getParent(),self._fileSystem)
    
    def createFile(self,fileContent):
        
        self.getParent().makedir()
        f=file( self._getLocalPath(), 'wb+' )
        try:
            f.write( fileContent )
        except Exception ,e:
            raise Exception,"createFile"+filePath+"\n inner exception:"+str(e)
        f.close()
    
    def fetchInfo(self): 
        result= FileInfo(self.getName())
        if not os.path.exists(self._getLocalPath()):
            result.exists=False
            return result
        
        #now ,exists
        result.exists=True
        
        if os.path.isdir(self._getLocalPath()):
            result.isFile =False
            result.isDir =True
            return result
        
        #now,it is file:
        if os.path.isfile(self._getLocalPath()):
            result.isFile =True
            result.isDir =False
            fileStats = os.stat ( self._getLocalPath() )
            result.size = fileStats [stat.ST_SIZE]
            result.modifyTime =  fileStats [stat.ST_MTIME]
            
        return result
    
class LocalFileSystem(FileSystem):
    def getFileStore(self,path):
        assert isinstance(path,Path2)
        
        return LocalFileStore(path,self)
    
    def getScheme(self):
        return 'file'